import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/putaway/putawaydialogscreen.dart';
import 'package:opene/ui/putaway/putawaymodel.dart';
import 'package:toast/toast.dart';

class InventoryPutawayLocationScreen extends StatelessWidget {
  PutatayPOL3 putatayPOL3;

  InventoryPutawayLocationScreen({this.putatayPOL3});

  @override
  Widget build(BuildContext context) {
    return InventoryPutawayLocationScreenPage(putatayPOL3: putatayPOL3);
  }
}

class InventoryPutawayLocationScreenPage extends StatefulWidget {
  PutatayPOL3 putatayPOL3;

  InventoryPutawayLocationScreenPage({this.putatayPOL3});

  @override
  _InventoryPutawayLocationPageState createState() => _InventoryPutawayLocationPageState(putatayPOL3: putatayPOL3);
}

class _InventoryPutawayLocationPageState extends BaseState<InventoryPutawayLocationScreen> {
  PutatayPOL3 putatayPOL3;

  _InventoryPutawayLocationPageState({this.putatayPOL3});

  List<PutawayLPNSkus> data = new List();
  String LpnContainer = "";
  List<PutawayLpn> tallyLpnInfoRespVos = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Putaway:Location";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    next = "Submit";
    data = putatayPOL3.skuAndQtyReqVos;
    tallyLpnInfoRespVos = putatayPOL3.tallyLpnInfoRespVos;
    if ((tallyLpnInfoRespVos != null) && (tallyLpnInfoRespVos.length > 0)) {
      LpnContainer = "Pending ${putatayPOL3.lpn} in ${tallyLpnInfoRespVos[0].containerNo} :";
    }
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15),
            child: Row(
              children: [
                Text(
                  "IBLPN: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
                Text(
                  Utils.getStringisEmpty(putatayPOL3.lpn),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15),
            child: Row(
              children: [
                Image.asset(
                  'assets/images/ic_recommended.png',
                  width: 15,
                  height: 15,
                ),
                Expanded(
                  flex: 1,
                  child: Text(
                    " Location: ${Utils.getStringisEmpty(putatayPOL3.prescribedLocation)}",
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    abnormal();
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 5, right: 5, top: 2, bottom: 2),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.all(Radius.circular(10.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.red, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'full load',
                      style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  racking();
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        racking();
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "please scan location",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 15, right: 15),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    "SKU",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    "QTY",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 15),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PutawayLPNSkus tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    Utils.getStringisEmpty(tally.sku),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    Utils.getStringisInteger(tally.quantity),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void abnormal() async {
    PutatayFeedbackQr putatayFeedbackQr = new PutatayFeedbackQr();
    putatayFeedbackQr.status = "full";
    putatayFeedbackQr.location = putatayPOL3.prescribedLocation;
    // 显示加载中对话框
    LoadingIndicator.show(context);
    String json = jsonEncode(putatayFeedbackQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.abnormal, method: BaseMethod.put, data: json);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      putaway(putatayPOL3.lpn);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void putaway(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;
    map["inventoryType"] = "1";
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.inventoryPutawayDetail, params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      putatayPOL3 = PutatayPOL3.fromJson(baseResponse.data);
      setState(() {
        putatayPOL3.lpn = lpn;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void racking() async {
    PutawayLocationQr putatayFeedbackQr = new PutawayLocationQr();
    putatayFeedbackQr.location = textEditingController.text;
    putatayFeedbackQr.prescribedLocation = putatayPOL3.prescribedLocation;
    putatayFeedbackQr.inbound_lpn = putatayPOL3.lpn;
    putatayFeedbackQr.version = 1;
    // 显示加载中对话框
    LoadingIndicator.show(context, title: "Submit...");
    String json = jsonEncode(putatayFeedbackQr);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.inventoryPutaway, method: BaseMethod.post, data: json);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      showDialog(
        context: context,
        barrierDismissible: false, // 设置背景不可点击
        builder: (context) => PutawaySucceedDialog(lpn: putatayPOL3.lpn,),
      ).then((value) => {Navigator.pop(context, true)});
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan location", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if ((!Utils.isEmpty(putatayPOL3.prescribedLocation)) && (textEditingController.text != putatayPOL3.prescribedLocation)) {
      Toast.show("please input  the prescribed location", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    racking();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
